import { FC, useContext, useEffect, useMemo, useState } from 'react'

import { adminUsername } from '../../constants'
import { DataContext } from '../../logic/DataContext'
import './index.scss'
import { request } from '../../logic/request'

interface Props {
  finishedQuestions: ShuDuNS.ResultItemStr[]
}

interface ScoreNumS {
  id: string
  scoreNum: number
}

const ScoreItem: FC<ScoreNumS> = (props) => {
  const { id, scoreNum } = props

  return (
    <div className="resultItem">
      <div className="row1">玩家：{id.replace('www', '')}</div>
      <div className="duration">得分：{scoreNum}</div>
    </div>
  )
}

// 单个结果
const ResultItem: FC<ShuDuNS.ResultItemStr> = (props) => {
  const { id, level, duration } = props

  // 格式化之后的时长
  const formattedDuration = useMemo(() => {
    if (!duration) return 0
    // 把秒转换成形式： 分-秒
    const minute = Math.floor(duration / 60)
    const second = duration % 60
    return `${minute}分 ${second}秒`
  }, [duration])

  return (
    <div className="resultItem">
      <div className="row1">
        {id} 难度：{level}
      </div>
      <div className="duration">{formattedDuration}</div>
    </div>
  )
}

// 题目结果
const QuestionResult: FC<Props> = (props) => {
  const { finishedQuestions } = props

  // main 权限下，需要展示所有用户的得分情况
  const [allResult, setAllResult] = useState<ScoreNumS[]>([])

  const { username } = useContext(DataContext)
  const isMain = useMemo(() => username === adminUsername, [username])

  // 通过接口来获取数据
  function getResultData() {
    request({
      url: '/getAllScore'
    }).then((res: any) => {
      if (res) {
        // 把得分结构从对象变成数组，然后进行排序
        const { score = {} } = res
        const keys = Reflect.ownKeys(score)
        const allResultArr: ScoreNumS[] = keys.map((key) => ({
          id: key as string,
          scoreNum: score[key]
        }))

        setAllResult(allResultArr.sort((a, b) => b.scoreNum - a.scoreNum))
      }
    })
  }

  useEffect(() => {
    if (isMain) {
      const timer = setInterval(() => {
        getResultData()
      }, 3000)
      return () => {
        clearInterval(timer)
      }
    }
  }, [isMain])

  return (
    <div className="questionResult">
      <h3>结果展示</h3>
      {isMain
        ? allResult.map((item) => <ScoreItem key={item.id} {...item} />)
        : finishedQuestions.map((item) => (
            <ResultItem key={item.id} {...item} />
          ))}
    </div>
  )
}

export default QuestionResult
